<!--
 * @Author: your name
 * @Date: 2024-04-11 10:04:09
 * @LastEditTime: 2024-04-11 20:37:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /quanguocheng-web-vue3/src/components/ScreenAdapter/index.vue
-->
<template>
  <div class="screenAdapter" :style="!props.elementDom && style">
    <slot></slot>
  </div>
</template>

<script setup name="ScreenAdapter">
  const props = defineProps({
    elementDom: {
      type: String,
    },
  });
  const style = reactive({
    // width: props.width + 'px',
    // height: props.height + 'px',
    transform: 'scale(1)',
  });
  watch(
    () => style,
    () => {
      if (props.elementDom) {
        nextTick(() => {
          console.log(document.querySelector(props.elementDom));
          const dom = document.querySelector(props.elementDom);
          // 保留原有style 覆盖一下
          dom.setAttribute('style', dom.getAttribute('style') + ';transform:' + style.transform);
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  onMounted(() => {
    setScale();
    window.onresize = Debounce(setScale, 1000);
  });
  // 获取放大缩小比例
  function getScale() {
    const w = document.documentElement.clientWidth / 1920;
    const h = document.documentElement.clientHeight / 1080;
    return w < h ? w : h;
  }
  // 设置比例
  function setScale() {
    style.transform = 'scale(' + getScale() + ')';
  }
  //防抖
  function Debounce(fn, t) {
    const delay = t || 500;
    let timer;
    return function () {
      const args = arguments;
      if (timer) {
        clearTimeout(timer);
      }
      const context = this;
      timer = setTimeout(() => {
        timer = null;
        fn.apply(context, args);
      }, delay);
    };
  }
</script>

<style lang="scss" scoped>
  .screenAdapter {
    //transform-origin: 0 0;
    //position: absolute;
    //left: 50%;
    //top: 50%;
    //transition: 0.3s;
    //   background: red;
  }
</style>
